package com.czwx.bee.business.manager.config.redis;

import cn.hutool.core.lang.Assert;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

/**
 * redis 前缀配置
 */
@Component
public class MyStringSerializer implements RedisSerializer<String> {

    private org.slf4j.Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${spring.cache.redis.key-prefix}")
    private String keyPrefix;

    private final Charset charset;
 
    public MyStringSerializer() {
        this ( Charset.forName ( "UTF8" ) );
    }
 
    public MyStringSerializer(Charset charset) {
        Assert.notNull ( charset, "Charset must not be null!" );
        this.charset = charset;
    }
 
    @Override
    public String deserialize(byte[] bytes) {
        String saveKey = new String ( bytes, charset );
        int indexOf = saveKey.indexOf ( keyPrefix );
        if (indexOf > 0) {
            log.info ( "key缺少前缀" );
        } else {
            saveKey = saveKey.substring ( indexOf );
        }
        return (saveKey.getBytes () == null ? null : saveKey);
    }
 
    @Override
    public byte[] serialize(String string) {
        String key = keyPrefix + string;
        return (key == null ? null : key.getBytes ( charset ));
    }
}